package com.twu.biblioteca;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.collect.Iterables.tryFind;

public class UserCenter {
    public static final int INIT_LIBRARY_NUMBER = 1111111;
    private static UserCenter instance;
    private int currentLibraryNumber;
    private List<User> users;
    private User loginUser;

    static {
        instance = new UserCenter();
    }

    private UserCenter() {
        currentLibraryNumber = INIT_LIBRARY_NUMBER;
        users = new ArrayList<User>();
    }

    public static UserCenter getInstance() {
        return instance;
    }

    public void addUserWithDefaultUsernameAndPassword(User u) {
        u.username(format(currentLibraryNumber))
                .password(format(currentLibraryNumber))
                .phone(nullToEmpty(u.getPhone()))
                .email(nullToEmpty(u.getEmail()));
        currentLibraryNumber++;

        users.add(u);
    }

    public boolean login(final String username, final String password) {
        Optional<User> user = tryFind(users, new Predicate<User>() {
            @Override
            public boolean apply(User u) {
                return u.getUsername().equals(username) && u.getPassword().equals(password);
            }
        });
        loginUser = user.orNull();
        return user.isPresent();
    }

    public List<User> getUsers() {
        return users;
    }

    public boolean haveLogin() {
        return loginUser != null;
    }

    public void clear() {
        currentLibraryNumber = INIT_LIBRARY_NUMBER;
        users.clear();
        loginUser = null;
    }

    public User getLoginUser() {
        return loginUser;
    }

    private static String format(int i) {
        return (i / 10000) + "-" + (i % 10000);
    }
}
